<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="130px">
      <el-form-item label="护理项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          style="width: 200px"
          clearable>
          <el-option
            v-for="dict in sys_nurse_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 中间操作按钮区域 -->
    <el-row :gutter="10" class="mb8" style="margin: 10px 0">
      <el-col :span="24" style="text-align: right">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['service:item:add']"
          >新增护理项目</el-button
        >
      </el-col>
    </el-row>

    <!-- 表格展示区域 -->
    <el-table v-loading="loading" :data="itemList">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="护理项目名称" align="center" prop="name" />
      <el-table-column label="价格(元)" align="center" prop="price" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_nurse_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="danger"
            :disabled="scope.row.disable"
            @click="handleDelete(scope.row)"
            v-hasPermi="['service:item:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            :disabled="scope.row.disable"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['service:item:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            :disabled="scope.row.disable"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['service:item:remove']">
            {{ scope.row.status === 0 ? "启用" : "停用" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改护理项目对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="itemRef" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="护理项目名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入"
            maxlength="10"
            show-word-limit />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input
            v-model="form.price"
            placeholder="请输入价格(元) 最多两位小数"
            @input="validatePrice"
            @blur="validatePrice" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input
            v-model="form.unit"
            placeholder="请输入单位"
            maxlength="5"
            show-word-limit />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_nurse_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="护理描述信息" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            maxlength="50"
            show-word-limit
            style="resize: none !important" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Item">
import {
  listItem,
  getItem,
  delItem,
  addItem,
  updateItem,
  getRelItemIds,
} from "@/api/service/item";

const { proxy } = getCurrentInstance();
const { sys_nurse_status } = proxy.useDict("sys_nurse_status");

//用来存储表格中的数据
const itemList = ref([]);
//控制显示添加或修改护理项目对话框
const open = ref(false);
//表格数据显示加载中
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
//分页插件总个数
const total = ref(0);
//编辑框标题
const title = ref("");
//接收与护理计划关联的护理项目id
const relItemIds = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
  },
  //编辑框表单校验规则
  rules: {
    name: [
      { required: true, message: "护理项目名称不能为空", trigger: "blur" },
      {
        min: 1,
        max: 10,
        message: "护理项目名称长度必须在1到10个字符之间",
        trigger: "blur",
      },
    ],
    price: [
      { required: true, message: "价格不能为空", trigger: "blur" },
      {
        pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/,
        message: "价格必须是数字，最多保留两位小数",
        trigger: "blur",
      },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" },
      {
        min: 1,
        max: 5,
        message: "单位长度必须在1到5个字符之间",
        trigger: "blur",
      },
    ],
    remark: [
      { required: true, message: "护理描述信息不能为空", trigger: "blur" },
      {
        min: 1,
        max: 50,
        message: "护理描述信息长度必须在1到50个字符之间",
        trigger: "blur",
      },
    ],
    image: [{ required: true, message: "图片不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询护理项目列表 */
function getList() {
  loading.value = true;
  //同时查询护理项目集合以及与护理计划关联的护理项目id
  Promise.all([listItem(queryParams.value), getRelItemIds()])
    .then(([itemResponse, relItemResponse]) => {
      itemList.value = itemResponse.rows;
      total.value = itemResponse.total;

      //将与护理计划关联的护理项目id存储到ids数组中
      relItemIds.value = relItemResponse.data || [];

      //根据与护理计划关联的护理项目id判断是否添加禁用属性
      itemList.value.forEach((item) => {
        const itemId = parseInt(item.id);
        if (relItemIds.value.includes(itemId)) {
          item.disable = true;
        } else {
          item.disable = false;
        }
      });
    })
    .catch((error) => {
      proxy.$modal.msgError(error.message);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 编辑框表单重置
function reset() {
  //清空form中的数据
  form.value = {
    id: null,
    name: null,
    sortOrder: null,
    unit: null,
    price: null,
    image: null,
    requirements: null,
    status: 1,
    createdBy: null,
    updatedBy: null,
    remark: null,
    createdAt: null,
    updatedAt: null,
    serviceTime: null,
    executionTimes: null,
    executionCycle: null,
  };
  proxy.resetForm("itemRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  //重置搜索表单的校验规则和数据
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加护理项目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getItem(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改护理项目";
  });
}

/** 点击确定提交按钮 */
function submitForm() {
  proxy.$refs["itemRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateItem(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addItem(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除护理项目编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delItem(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/**修改启用禁用状态 */
function handleChangeStatus(row) {
  proxy.$modal
    .confirm(
      `是否确认${row.status === 0 ? "启用" : "停用"}护理项目编号为"${
        row.id
      }"的数据项？`
    )
    .then(function () {
      return updateItem({
        id: row.id,
        status: row.status === 0 ? 1 : 0,
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess(`${row.status === 0 ? "启用" : "停用"}成功`);
    })
    .catch(() => {});
}

/** 校验价格输入 */
function validatePrice() {
  let price = form.value.price;

  // 如果为空，不进行校验
  if (!price) {
    return;
  }

  // 移除非数字和小数点的字符
  price = price.toString().replace(/[^\d.]/g, "");

  // 确保只有一个小数点
  const parts = price.split(".");
  if (parts.length > 2) {
    price = parts[0] + "." + parts.slice(1).join("");
  }

  // 限制小数点后最多两位
  if (parts.length === 2 && parts[1].length > 2) {
    price = parts[0] + "." + parts[1].substring(0, 2);
  }

  // 确保不以小数点开头
  if (price.startsWith(".")) {
    price = "0" + price;
  }

  // 移除开头的多个0（但保留单个0）
  if (price.length > 1 && price.startsWith("0") && !price.startsWith("0.")) {
    price = price.replace(/^0+/, "") || "0";
  }

  // 更新表单值
  form.value.price = price;
}

getList();
</script>
